package Day19;

public class Demo07 {
    public static void main(String[] args) {
        //线程安全问题
        //解决方案一：同步代码块  synchronized
        //格式: synchronized(锁对象){} 任何对象都能作为锁对象
        //看同一把锁
        Ticket tk = new Ticket();
        Thread t = new Thread(tk);
        Thread a = new Thread(tk);
        Thread b = new Thread(tk);
        a.start();
        b.start();
        t.start();
    }
    static class Ticket implements Runnable{
        private int count = 10;
        private Object o = new Object();
        @Override
        public void run() {
                while (true) {
//                    synchronized (o) {
//                    if (count > 0) {
//                        System.out.println("正在准备卖票");
//                        try {
//                            Thread.sleep(1000);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                        count--;
//                        System.out.println(Thread.currentThread().getName() + "出票成功,余票：" + count);
//                    } else {
//                        break;
//                    }
//                }
                    boolean b = sale();
                    if(b != true){
                        break;
                    }
            }
        }
        //线程安全方案二：同步方法
        public synchronized boolean sale() {
            if (count > 0) {
                System.out.println("正在准备卖票");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count--;
                System.out.println(Thread.currentThread().getName() + "出票成功,余票：" + count);
                return true;
            }
            return false;
        }
    }
}
